<?php
/**
 * 邮箱模型
 * 
 * @package ews
 * @ews Enterprise WorkShop
 * @version 1.0 alpha
 * @since 2011-06-01
 * @author chenyan
 */

class mailerModel extends model
{
	/**************************************************************************
	 * 邮箱配置返回 值说明
	 * 1.返回的数组（mailer）说明
	 *   mailer_id			int			邮箱ID
	 *   user_id			int			邮箱所有者ID
	 *   email				string		邮地址
	 *   login_name			string		登陆名
	 *   login_password		string		登陆密码（明文）
	 *   mailer_type		string		邮件服务商
	 *   pop_type			string		pop3/imap
	 *   pop_server			string		接收邮件服务器
	 *   pop_port			int			接收邮件服务器端口
	 *   smtp_server		string		发送邮件服务器
	 *   smtp_port			int			发送邮件服务器端口
	 *   is_ssl				int			是否加密发送				1：是  0：否 
	 * 
	 * 2.若返回值为操作是否成功	1：成功      0或则负数：失败
	 **************************************************************************/
	
	/**************************************************************************/
	/*
	/*邮箱配置部分
	/*
	/**************************************************************************/
	
	
	/**
	 * 创建邮箱
	 * @param int $user_id				邮箱所有者ID
	 * @param string $email				邮地址
	 * @param string $login_name		登陆名
	 * @param string $login_password	登陆密码（明文）
	 * @param string $mailer_type		邮件服务商
	 * @param string $pop_type			pop3/imap
	 * @param string $pop_server		接收邮件服务器
	 * @param int $pop_port				接收邮件服务器端口
	 * @param string $smtp_server		发送邮件服务器
	 * @param int $smtp_port			发送邮件服务器端口
	 * @param int $is_ssl				是否加密发送				1：是  0：否
	 * 
	 * @return	非零整数：新插入记录ID     -1：email地址有误	
	 */
	public function add($user_id,$email,$login_name,$login_password,$mailer_type,$pop_type,$pop_server,$pop_port,
					$smtp_server,$smtp_port,$is_ssl){
						
		if(!preg_match('/^[a-z]([a-z0-9]*[-_\.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?$/i', $email)){
			return -1;	//email地址有误
		}
		$data = array('user_id'=>$user_id,'email'=>$email,'login_name'=>$login_name,'login_password'=>$login_password,
					'mailer_type'=>$mailer_type,'pop_type'=>$pop_type,'pop_server'=>$pop_server,'pop_port'=>$pop_port,
					'smtp_server'=>$smtp_server,'smtp_port'=>$smtp_port,'is_ssl'=>$is_ssl,'last_mail_date'=>'1900-01-01 00:00:00',
					'last_mail_num'=>0);
		$id = DB::insert('mailer', $data);
		
		return $id;
	}
	
	/**
	 * 修改邮箱
	 * @param int $mailer_id			邮箱ID
	 * @param int $user_id				邮箱所有者ID
	 * @param string $email				邮地址
	 * @param string $login_name		登陆名
	 * @param string $login_password	登陆密码（明文）
	 * @param string $mailer_type		邮件服务商
	 * @param string $pop_type			pop3/imap
	 * @param string $pop_server		接收邮件服务器
	 * @param int $pop_port				接收邮件服务器端口
	 * @param string $smtp_server		发送邮件服务器
	 * @param int $smtp_port			发送邮件服务器端口
	 * @param int $is_ssl				是否加密发送				1：是  0：否
	 * 
	 * @return 	int		1:成功     0：失败	
	 */
	public function modify($mailer_id,$user_id,$email,$login_name,$login_password,$mailer_type,$pop_type,$pop_server,$pop_port,
					$smtp_server,$smtp_port,$is_ssl){

		if(!preg_match('/^[a-z]([a-z0-9]*[-_\.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?$/i', $email)){
			return -1;	//email地址有误
		}
		$data = array('user_id'=>$user_id,'email'=>$email,'login_name'=>$login_name,'login_password'=>$login_password,
					'mailer_type'=>$mailer_type,'pop_type'=>$pop_type,'pop_server'=>$pop_server,'pop_port'=>$pop_port,
					'smtp_server'=>$smtp_server,'smtp_port'=>$smtp_port,'is_ssl'=>$is_ssl);
		$condition = "mailer_id=$mailer_id";
		$row = DB::update('mailer',$data,$condition);
		if($row>0) return 1;
		else return 0;			
						
	}
	
	/**
	 * 根据邮箱ID获取邮箱信息
	 * @param int $mailer_id	邮箱ID
	 * 
	 * @return	一维数组
	 */
	public function get_mailer_by_mailer_id($mailer_id){
		$row = DB::fetchOne('SELECT * FROM '.DB::table('mailer').' WHERE mailer_id = '.$mailer_id);
		if(count($row) == 0){
			return array();
		}
		return $row;
	}
	
	/**
	 * 根据用户ID获取邮箱信息
	 * @param int $user_id	用户ID
	 * 
	 * @return	二维数组
	 */
	public function get_mailers_by_user_id($user_id){
		$row = DB::fetchArray('SELECT * FROM '.DB::table('mailer').' WHERE user_id = '.$user_id);
		return $row;
	}
	
	/**
	 * 根据用户ID获取邮箱个数
	 * @param int $user_id	用户ID
	 * 
	 * @return	int	邮箱个数
	 */
	public function get_mailer_count_by_user_id($user_id){
		$row = DB::fetchOne('SELECT count(*) as num FROM '.DB::table('mailer').' WHERE user_id = '.$user_id);
		return $row['num'];
	}
	
	
	/**************************************************************************/
	/*
	/*收件箱部分
	/*
	/**************************************************************************/

	/**
	 * 收取用户ID为$user_id的邮件
	 * 
	 * @param unknown_type $user_id 	收取的用户ID
	 */
	public function receive($user_id){
		$mailers = $this->get_mailers_by_user_id($user_id);
		$mailboxRow=$mailers[0];
		
		@include_once ROOT.'source/lib/receivemailer/receivemail.class.php';
		@include_once ROOT.'source/lib/receivemailer/decodemail.class.php';

		$mailboxid =  $mailboxRow['mailer_id'];
		$receiveserver = $mailboxRow['pop_server'];
		$receiveserverport = $mailboxRow['pop_port'];
		$receiveservertype = $mailboxRow['pop_type'];
		$username  = $mailboxRow['login_name'];
		$password = $mailboxRow['login_password'];
		$mailaddress = $mailboxRow['email'];
		$displayname = $mailboxRow['email'];
		$is_ssl=$mailboxRow['is_ssl']=='1'?true:false;
		$last_mail_date = $mailboxRow['last_mail_date'];
		$last_mail_num = $mailboxRow['last_mail_num'];
		/*****邮件接收*****/
		
		$obj = new receiveMail($username,$password,$mailaddress,$receiveserver,$receiveservertype,$receiveserverport,$is_ssl); 
		//连接到邮件服务器
		if(!$obj->connect())         //If connection fails give error message and exit 
			return -2;
			
		$date=date("d-M-Y",strtotime(substr($last_mail_date,0,10)));
		$mails = $obj->getMailsByTime($date);
		$cur_mail_max_num = $mails[count($mails)-1];
		
		$mimedecode = new MimeDecode();//用于解析头部的乱码信息
		
		foreach($mails as $i)
		//for($i = $last_mail_num+1 ; $i <= $cur_mail_max_num; $i++) 
		{ 
			if($i<=$last_mail_num) continue;
		    /*****获取邮件头与正文*****/
			$head = $obj->getHeaders($i);  		// 读取获取邮件头信息，返回数组 **数组键值为 (subject,to,toOth,toNameOth,from,fromName)
			//获取邮件头详细信息
			$subject = addslashes($mimedecode->mime_decode($head['subject']));	//主题
			$from = addslashes($mimedecode->mime_decode($head['from']));											//发件人 
			$fromname = addslashes($mimedecode->mime_decode($head['fromName']));	//发件人名称
			$to = $mailboxRow['mail_address'];										//收件人 
			$toother = addslashes($mimedecode->mime_decode(($head['toOth'])));
			$size = $head['size'];
			$receivetime = $head['date'];				//标准时间
			//获取邮件正文			
			$content = $obj->getBody($i);

			$cur_mail_encoding = mb_detect_encoding($subject);
			if($cur_mail_encoding!='UTF-8'|| $cur_mail_encoding!='utf-8'){
				$subject=iconv( $cur_mail_encoding,'utf-8',$subject);
				$from=iconv( $cur_mail_encoding, 'utf-8',$from);
				$fromname=iconv( $cur_mail_encoding, 'utf-8',$fromname);
				$to=iconv( $cur_mail_encoding, 'utf-8',$to);
				$to=iconv( $cur_mail_encoding, 'utf-8',$toother);
				$content=iconv( $cur_mail_encoding, 'utf-8', $content);
			}
			
			//邮件内容写入文件
			$content_file_name="/mailer_content_".rand().time().".html";
			$content_file=MAILER_CONTENT_PAHT.$content_file_name;
			$fp=fopen($content_file,"w");
			fputs($fp,$content);
			fclose($fp);
			unset($content);

			//入收件箱库
			$data = array("`from`"=>$from,"from_name"=>$fromname,"`to`"=>$to,"to_other"=>$toother,
						"subject"=>$subject,"content_file"=>MAILER_CONTENT_REL_PAHT.$content_file_name,
						"mktime"=>strtotime($receivetime),"size"=>$size,
						"attachement_count"=>0,"mailer_id"=>$mailboxid,"message_id"=>$head['messageid']);
			$mailer_item_id = DB::insert("mailer_item",$data);
			$data = array("mailer_id"=>$mailboxid,"mailer_item_id"=>$mailer_item_id,"has_read"=>0);
			DB::insert("mailer_inbox",$data);

			//获取附件信息
			$cur_attachpath = MAILER_ATTACHMENT_PAHT."/$user_id/$mailboxid/r/$mailid/";
			if(!is_dir($cur_attachpath)) mkdir($cur_attachpath,0777,true);
			$attachstr = $obj->GetAttach($i,$cur_attachpath); 	// 获取邮件附件，返回的文件名以逗号隔开。 例如. (mailid, Path to store file) 
			$attacharr = explode(",",$attachstr);	//附件数组

			//存储附件信息
			$attachcount =0;
			foreach($attacharr as $key=>$value){ 
				if(empty($value)||$value==null) continue;
				$filename = $mimedecode->mime_decode($value);
				$cur_mail_encoding = mb_detect_encoding($filename);
				if($cur_mail_encoding!='UTF-8'|| $cur_mail_encoding!='utf-8'){
					$filename=iconv( $cur_mail_encoding,'utf-8',$filename);
				}
				$filepath = MAILER_ATTACHMENT_REL_PAHT."/$user_id/$mailboxid/r/$mailid/$value";
				$attachmentsize=filesize(MAILER_ATTACHMENT_PAHT."/$user_id/$mailboxid/r/$mailid/$value");
				$attachmentsize = (empty($attachmentsize)||$attachmentsize==null)?0:$attachmentsize;
				$data = array("file_name"=>$filename,"file_path"=>$filepath,"file_size"=>$attachmentsize,
							"mailer_item_id"=>$mailer_item_id);
				DB::insert("mailer_attachment",$data);
				$attachcount++;
			}
			//更新收件箱是否有附件
			if($attachcount>0){
				$data = array("attachement_count"=>$attachcount);
				$condition = "mailer_item_id = $mailer_item_id";
				DB::update("mailer_item",$data,$condition);
			}

			//更新邮箱信息
			$data = array("last_mail_date"=>date('Y-m-d H:m:s',strtotime($receivetime)),"last_mail_num"=>$i);
			$condition = "mailer_id = $mailboxid";
			DB::update("mailer",$data,$condition);
		}
		
		
		$obj->close_mailbox();   //Close Mail Box
		
		return 1;
	}
	
	/**
	 * 获取用户ID为$user_id的邮件总数
	 * 
	 * @param unknown_type $user_id 收取的用户ID
	 */
	public function last_mail_count($user_id){
		$mailers = $this->get_mailers_by_user_id($user_id);
		$mailboxRow=$mailers[0];
		if(count($mailboxRow)==0) return -1;
		
		@include_once ROOT.'source/lib/receivemailer/receivemail.class.php';
		
		$mailboxid =  $mailboxRow['mailer_id'];
		$receiveserver = $mailboxRow['pop_server'];
		$receiveserverport = $mailboxRow['pop_port'];
		$receiveservertype = $mailboxRow['pop_type'];
		$username  = $mailboxRow['login_name'];
		$password = $mailboxRow['login_password'];
		$mailaddress = $mailboxRow['email'];
		$displayname = $mailboxRow['email'];
		$is_ssl=$mailboxRow['is_ssl']=='1'?true:false;
		$last_mail_date = $mailboxRow['last_mail_date'];
		$last_mail_num = $mailboxRow['last_mail_num'];
	
		/*****邮件接收*****/
		$obj = new receiveMail($username,$password,$mailaddress,$receiveserver,$receiveservertype,$receiveserverport,$is_ssl); 
		//连接到邮件服务器

		if(!$obj->connect())         //If connection fails give error message and exit 
			return -2;

		$date=date("d-M-Y",strtotime(substr($last_mail_date,0,10)));
		$mails = $obj->getMailsByTime($date);

		if(empty($mails)){
			$tot = 0;
		}elseif($mails[0]>$last_mail_num){
			$tot = count($mails); 
		}else{
			for($i=0;$last_mail_num>$mails[$i];$i++);
			$tot = count($mails)-($i+1);
		}
		//读取未读邮件数 

		$obj->close_mailbox();   //Close Mail Box
		return $tot;
	}
	/**
	 * 获取用户ID为$user_id的邮件总数
	 * 
	 * @param unknown_type $user_id 	收取的用户ID
	 * @param unknown_type $start 		邮件起始编号
	 * @param unknown_type $end 		邮件结束编号$start>$end
	 */
	public function receive_by_number($user_id,$start,$end){
		$mailers = $this->get_mailers_by_user_id($user_id);
		$mailboxRow=$mailers[0];
		
		@include_once ROOT.'source/lib/receivemailer/receivemail.class.php';
		@include_once ROOT.'source/lib/receivemailer/decodemail.class.php';

		$mailboxid =  $mailboxRow['mailer_id'];
		$receiveserver = $mailboxRow['pop_server'];
		$receiveserverport = $mailboxRow['pop_port'];
		$receiveservertype = $mailboxRow['pop_type'];
		$username  = $mailboxRow['login_name'];
		$password = $mailboxRow['login_password'];
		$mailaddress = $mailboxRow['email'];
		$displayname = $mailboxRow['email'];
		$is_ssl=$mailboxRow['is_ssl']=='1'?true:false;
		$last_mail_date = $mailboxRow['last_mail_date'];
		$last_mail_num = $mailboxRow['last_mail_num'];
		/*****邮件接收*****/
		$obj = new receiveMail($username,$password,$mailaddress,$receiveserver,$receiveservertype,$receiveserverport,$is_ssl); 
		//连接到邮件服务器
		if(!$obj->connect())         //If connection fails give error message and exit 
			return -2;
		
		$mimedecode = new MimeDecode();//用于解析头部的乱码信息
		for($i = $start; $i >= $end; $i--) 
		{ 
		 /*****获取邮件头与正文*****/
			$head = $obj->getHeaders($i);  		// 读取获取邮件头信息，返回数组 **数组键值为 (subject,to,toOth,toNameOth,from,fromName)
			
			//获取邮件头详细信息
			$subject = addslashes($mimedecode->mime_decode($head['subject']));	//主题
			$from = addslashes($mimedecode->mime_decode($head['from']));											//发件人 
			$fromname = addslashes($mimedecode->mime_decode($head['fromName']));	//发件人名称
			$to = $mailboxRow['mail_address'];										//收件人 
			$toother = addslashes($mimedecode->mime_decode(($head['toOth'])));
			$size = $head['size'];
			$receivetime = $head['date'];				//标准时间
			//获取邮件正文			
			$content = $obj->getBody($i);

			$cur_mail_encoding = mb_detect_encoding($subject);
			if($cur_mail_encoding!='UTF-8'|| $cur_mail_encoding!='utf-8'){
				$subject=iconv( $cur_mail_encoding,'utf-8',$subject);
				$from=iconv( $cur_mail_encoding, 'utf-8',$from);
				$fromname=iconv( $cur_mail_encoding, 'utf-8',$fromname);
				$to=iconv( $cur_mail_encoding, 'utf-8',$to);
				$to=iconv( $cur_mail_encoding, 'utf-8',$toother);
				$content=iconv( $cur_mail_encoding, 'utf-8', $content);
			}
			//邮件内容写入文件
			$content_file=MAILER_CONTENT_PAHT."/mailer_content_".rand().time().".html";
			$fp=fopen($content_file,"w");
			fputs($fp,$content);
			fclose($fp);
			unset($content);

			//入收件箱库
			$data = array("`from`"=>$from,"from_name"=>$fromname,"`to`"=>$to,"to_other"=>$toother,
						"subject"=>$subject,"content_file"=>MAILER_CONTENT_REL_PAHT.$content_file_name,
						"mktime"=>strtotime($receivetime),"size"=>$size,
						"attachement_count"=>0,"mailer_id"=>$mailboxid,"message_id"=>$head['messageid']);
			$mailer_item_id = DB::insert("mailer_item",$data);
			$data = array("mailer_id"=>$mailboxid,"mailer_item_id"=>$mailer_item_id,"has_read"=>0);
			DB::insert("mailer_inbox",$data);

			//获取附件信息
			$attachmentFold="/$user_id/$mailboxid/r/$mailid/";
			
			$cur_attachpath = MAILER_ATTACHMENT_PAHT.$attachmentFold;
			if(!is_dir($cur_attachpath)) mkdir($cur_attachpath,0777,true);
			$attachstr = $obj->GetAttach($i,$cur_attachpath); 	// 获取邮件附件，返回的文件名以逗号隔开。 例如. (mailid, Path to store file) 
			$attacharr = explode(",",$attachstr);	//附件数组

			//存储附件信息
			$attachcount =0;
			foreach($attacharr as $key=>$value){ 
				if(empty($value)||$value==null) continue;
				$filename = $mimedecode->mime_decode($value);
				$cur_mail_encoding = mb_detect_encoding($filename);
				if($cur_mail_encoding!='UTF-8'|| $cur_mail_encoding!='utf-8'){
					$filename=iconv( $cur_mail_encoding,'utf-8',$filename);
				}
				$filepath = MAILER_ATTACHMENT_REL_PAHT."/$user_id/$mailboxid/r/$mailid/$value";
				$attachmentsize=filesize(MAILER_ATTACHMENT_PAHT."/$user_id/$mailboxid/r/$mailid/$value");
				$attachmentsize = (empty($attachmentsize)||$attachmentsize==null)?0:$attachmentsize;
				$data = array("file_name"=>$filename,"file_path"=>$filepath,"file_size"=>$attachmentsize,
							"mailer_item_id"=>$mailer_item_id);
				DB::insert("mailer_attachment",$data);
				$attachcount++;
			}
			//更新收件箱是否有附件
			if($attachcount>0){
				$data = array("attachement_count"=>$attachcount);
				$condition = "mailer_item_id = $mailer_item_id";
				DB::update("mailer_item",$data,$condition);
			}
			//更新邮箱信息
			$data = array("last_mail_date"=>date('Y-m-d H:m:s',strtotime($receivetime)),"last_mail_num"=>$i);
			$condition = "mailer_id = $mailboxid";
			DB::update("mailer",$data,$condition);
		} 
		$obj->close_mailbox();   //Close Mail Box
		return 1;
	}
	
	/**
	 * 收件箱信件列表
	 * 
	 * @param unknown_type $user_id		用户ID	
	 * @param unknown_type $receiveboxCount	结果总数
	 * @param unknown_type $totalpage		总页数
	 * @param unknown_type $pagesize	每页大小
	 * @param unknown_type $pagenum		页号
	 * @return $receiveboxArr 收件箱邮件数组
	 */
	public function receivebox($user_id,& $receiveboxCount,& $totalpage,& $pagesize,& $pagenum=1){
		$mailers = $this->get_mailers_by_user_id($user_id);
		$mailer_id=$mailers[0]['mailer_id'];
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('mailer_inbox')."  WHERE mailer_id = $mailer_id");
		$receiveboxCount = $row['num'];	
		//分页获取
		$totalpage = ceil($receiveboxCount / $pagesize);
		if($receiveboxCount==0) $totalpage++;
		$pagenum = max(1,$pagenum);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		$receiveboxArr = DB::fetchArray("SELECT * FROM ".DB::table('mailer_inbox')." AS i,".DB::table('mailer_item')." AS it WHERE i.mailer_item_id=it.mailer_item_id AND i.mailer_id = $mailer_id ORDER BY it.mktime DESC limit $limitstart,$pagesize");
		return $receiveboxArr;
	}
	
	/**
	 * 查看收件箱指定邮件（包括附件）
	 * 
	 * @param unknown_type $user_id		用户ID
	 * @param unknown_type $mailboxid	邮箱ID
	 * @param unknown_type $mailid		邮件ID
	 * @return $mailcontent 邮件详细信息
	 */
	public function viewreceivemail($user_id,$mailid){
		$mailers = $this->get_mailers_by_user_id($user_id);
		$mailer_id=$mailers[0]['mailer_id'];
		$mailcontent  = DB::fetchOne("SELECT * FROM ".DB::table('mailer_inbox')." AS i,".DB::table('mailer_item')." AS it WHERE i.mailer_item_id=it.mailer_item_id AND i.mailer_id = $mailer_id AND i.mailer_inbox_id=$mailid");
		if($mailcontent['attachement_count']>0){
			//附件
			$mailcontent['attachment'] = DB::fetchArray("SELECT * FROM ".DB::table('mailer_attachment')." WHERE mailer_item_id=".$mailcontent['mailer_item_id']);
		}
		//设置为已读
		$data = array("has_read"=>1);
		$condition = "mailer_inbox_id=$mailid";
		DB::update("mailer_inbox",$data,$condition);
		return $mailcontent;
	}
	
	/**
	 * 清空收件箱
	 * 
	 * @param unknown_type $user_id		用户ID
	 * @param unknown_type $mailboxid	邮箱ID
	 */
	public function clearreceivebox($user_id,$mailboxid){
		if(!$this->checkMailbox($user_id,$mailboxid,$mailboxRow)){
			return -1;//邮箱不存在
		}
		//删除附件文件夹
		$cur_attachpath = MAILER_ATTACHMENT_PAHT."/$user_id/$mailboxid/r/";
		if(is_dir($cur_attachpath)) $this->mailerDeleteDir($cur_attachpath);
		//删除所有附件信息   还未写
//		$condition="mailboxid=$mailboxid";
//		DB::delete("mailer_attachment",$condition);
		//删除所有邮件
		$condition="mailer_id=$mailboxid";
		DB::delete("mailer_inbox",$condition);
		//删除item表内容
		return 1;
	}
	
	/**
	 * 删除收件箱邮件
	 * 
	 * @param unknown_type $user_id		用户ID
	 * @param unknown_type $mailid		邮件ID
	 */
	public function deletereceivemail($user_id,$mailid){
		$mailers = $this->get_mailers_by_user_id($user_id);
		$mailer_id=$mailers[0]['mailer_id'];
		$cur_attachpath = MAILER_ATTACHMENT_PAHT."/$user_id/$mailer_id/r/$mailid/";
		if(is_dir($cur_attachpath)) $this->mailerDeleteDir($cur_attachpath);//删除附件文件夹
		$mail  = DB::fetchOne("SELECT * FROM ".DB::table('mailer_inbox')." WHERE mailer_id = $mailer_id AND mailer_inbox_id=$mailid");
		//删除附件信息
		$condition="mailer_item_id=".$mail['mailer_item_id'];
		DB::delete("mailer_attachment",$condition);
		//删除邮件
		$condition="mailer_item_id=".$mail['mailer_item_id'];
		DB::delete("mailer_item",$condition);
		$condition="mailer_id=$mailer_id AND mailer_inbox_id=$mailid";
		DB::delete("mailer_inbox",$condition);
		return 1;
	}
	/**************************************************************************/
	/*
	/*发件箱部分
	/*
	/**************************************************************************/
	
	
	/**
	 * 发送邮件
	 * 
	 * @param unknown_type $user_id 	发送的用户ID
	 * @param unknown_type $to			目标email地址
	 * @param unknown_type $subject 	主题
	 * @param unknown_type $body		内容
	 * @param unknown_type $attachment 	包含文件地址的数组，若没有附件，则为空(临时存储地址)
	 */
	public function send($user_id,$to,$subject,$body,$attachment){
		$mailboxRow=array();
		$mailers = $this->get_mailers_by_user_id($user_id);
		$mailboxRow=$mailers[0];
			
		@include_once ROOT.'source/lib/swiftmailer/swift_required.php';
		
		$attachmentsize=0;
		$tag="";
		$curtime = date("Y-m-d H:i:s");
		$contentbody = $body;
		$contentpart = $body;
		$toother="";
		$sendserverport = $mailboxRow['smtp_port'];
		$sendserver = $mailboxRow['smtp_server'];
		$username = $mailboxRow['login_name'];
		$password = $mailboxRow['login_password'];
		$from = $mailboxRow['email'];
		$displayname = $mailboxRow['login_name'];
		$is_ssl  = $mailboxRow['is_ssl'];
		$mailboxid=$mailboxRow['mailer_id'];
			
		/*****发送邮件*****/
		//Create the Transport
		if($is_ssl){
			$transport = Swift_SmtpTransport::newInstance($sendserver, $sendserverport,"ssl");
		}else{
			$transport = Swift_SmtpTransport::newInstance($sendserver, $sendserverport) ;
		}
		$transport->setUsername($username);
		$transport->setPassword($password); 
		//Create the Mailer using your created Transport
		$mailer = Swift_Mailer::newInstance($transport);
		//Create the message
		$message = Swift_Message::newInstance()
			->setCharset('utf-8')
			->setSubject($subject)
			->setFrom(array($from => $displayname))
			->setTo(array($to))
			->setBody($contentbody)
			->addPart($contentpart, 'text/html');
			
		$attachment_count=0;
		foreach($attachment as $am){
			if(empty($am)||$am=='') continue;
			$message->attach(Swift_Attachment::fromPath($am));
			$attachmentsize+=filesize($am);
			$attachment_count++;
		}

		//Send the message
		$result = $mailer->send($message);
		if($result<=0){							
			return -2;//发送失败
		}
		
		//邮件内容写入文件
		$content_file_name="/mailer_content_".rand().time().".html";
		$content_file=MAILER_CONTENT_PAHT.$content_file_name;
		$fp=fopen($content_file,"w");
		fputs($fp,$body);
		fclose($fp);
		unset($body);

		//入收件箱库
		$data = array("`from`"=>$from,"from_name"=>$username,"`to`"=>$to,"to_other"=>$toother,
					"subject"=>$subject,"content_file"=>MAILER_CONTENT_REL_PAHT.$content_file_name,
					"mktime"=>time(),"size"=>$attachmentsize,"message_id"=>"0",
					"attachement_count"=>$attachment_count,"mailer_id"=>$mailboxid);
		$mailer_item_id = DB::insert("mailer_item",$data);
		$data = array("mailer_id"=>$mailboxid,"mailer_item_id"=>$mailer_item_id);
		DB::insert("mailer_outbox",$data);
		unset($data);
		//入附件库
		$attachmentFold = "/$user_id/$mailboxid/s/$mailid/";
		if($attachment_count>0){
			foreach($attachment as $am){
				if(empty($am)||$am=='') continue;
				//存储附件
				$cur_attachpath = MAILER_ATTACHMENT_PAHT.$attachmentFold;
				if(!is_dir($cur_attachpath)) mkdir($cur_attachpath,0777,true);
				$tmp_attachmentstr = explode("/",$am);
				$attachmentname = $tmp_attachmentstr[count($tmp_attachmentstr)-1];
				$attachmentpath = $cur_attachpath.$attachmentname;
				$rel_filepath = MAILER_ATTACHMENT_REL_PAHT.$attachmentFold.$attachmentname;
				copy($am,$attachmentpath);
				$data = array("file_name"=>$attachmentname,"file_path"=>$rel_filepath,"file_size"=>$attachmentsize,
							"mailer_item_id"=>$mailer_item_id);
				DB::insert("mailer_attachment",$data);
			}			
		}
		return 1;
	}
	
	
	
	/**
	 * 发件箱信件列表
	 * 
	 * @param unknown_type $user_id		用户ID	
	 * @param unknown_type $sendboxCount	结果总数
	 * @param unknown_type $totalpage		总页数
	 * @param unknown_type $pagesize	每页大小
	 * @param unknown_type $pagenum		页号
	 * @return $sendboxArr 发件箱邮件数组
	 */
	public function sendbox($user_id,& $sendboxCount,& $totalpage,& $pagesize,& $pagenum=1){
		$mailers = $this->get_mailers_by_user_id($user_id);
		$mailer_id=$mailers[0]['mailer_id'];
		
		$row = DB::fetchOne("SELECT count(*) as num FROM ".DB::table('mailer_outbox')."  WHERE mailer_id = $mailer_id");
		$sendboxCount = $row['num'];	
		//分页获取
		$totalpage = ceil($sendboxCount / $pagesize);
		if($sendboxCount==0) $totalpage++;
		$pagenum = max(1,$pagenum);
		$pagenum = min($totalpage, $pagenum);
		$limitstart = ($pagenum-1)*$pagesize;
		$sendboxArr = DB::fetchArray("SELECT * FROM ".DB::table('mailer_outbox')." AS ou,".DB::table('mailer_item')." AS it WHERE ou.mailer_item_id=it.mailer_item_id AND ou.mailer_id = $mailer_id ORDER BY it.mktime DESC limit $limitstart,$pagesize");
		return $sendboxArr;
	}
	
	
	
	/**
	 * 查看发件箱指定邮件（包括附件）
	 * 
	 * @param unknown_type $user_id		用户ID
	 * @param unknown_type $mailid		邮件ID
	 * @return $mailcontent 邮件详细信息
	 */
	public function viewsendmail($user_id,$mailid){
		$mailers = $this->get_mailers_by_user_id($user_id);
		$mailer_id=$mailers[0]['mailer_id'];
		$mailcontent  = DB::fetchOne("SELECT * FROM ".DB::table('mailer_outbox')." AS o,".DB::table('mailer_item')." AS it WHERE o.mailer_item_id=it.mailer_item_id AND o.mailer_id = $mailer_id AND o.mailer_outbox_id=$mailid");
		if($mailcontent['attachement_count']>0){
			//附件
			$mailcontent['attachment'] = DB::fetchArray("SELECT * FROM ".DB::table('mailer_attachment')." WHERE mailer_item_id=".$mailcontent['mailer_item_id']);
		}
		return $mailcontent;
	}
	
	/**
	 * 清空发件箱
	 * 
	 * @param unknown_type $user_id		用户ID
	 * @param unknown_type $mailboxid	邮箱ID
	 */
	public function clearsendbox($user_id,$mailboxid){
		if(!$this->checkMailbox($user_id,$mailboxid,$mailboxRow)){
			return -1;//邮箱不存在
		}
		//删除附件文件夹
		$cur_attachpath = MAILER_ATTACHMENT_PAHT."/$user_id/$mailboxid/s/";
		if(is_dir($cur_attachpath)) $this->mailerDeleteDir($cur_attachpath);
		//删除所有附件信息
//		$condition="mailboxid=$mailboxid AND type='2'";
//		DB::delete("mailer_attachment",$condition);
		//删除所有邮件
		$condition="mailer_id=$mailboxid";
		DB::delete("mailer_outbox",$condition);
		//删除item表内容
		
		return 1;
	}
	
	/**
	 * 删除发件箱邮件
	 * 
	 * @param unknown_type $user_id		用户ID
	 * @param unknown_type $mailboxid	邮箱ID
	 * @param unknown_type $mailid		邮件ID
	 */
	public function deletesendmail($user_id,$mailid){
		$mailers = $this->get_mailers_by_user_id($user_id);
		$mailer_id=$mailers[0]['mailer_id'];
		$cur_attachpath = MAILER_ATTACHMENT_PAHT."/$user_id/$mailer_id/s/$mailid/";
		if(is_dir($cur_attachpath)) $this->mailerDeleteDir($cur_attachpath);//删除附件文件夹

		$mail=DB::fetchOne("SELECT * FROM ".DB::table('mailer_outbox')." WHERE mailer_id = $mailer_id AND mailer_outbox_id=$mailid");
		//删除附件信息
		$condition="mailer_item_id=".$mail['mailer_item_id'];
		DB::delete("mailer_attachment",$condition);
		//删除邮件
		$condition="mailer_item_id=".$mail['mailer_item_id'];
		DB::delete("mailer_item",$condition);
		$condition="mailer_id=$mailer_id AND mailer_outbox_id=$mailid";
		DB::delete("mailer_outbox",$condition);
		return 1;
	}
	
	/**
	 * 获取文件类型
	 * @param $file_name
	 */
	function get_type_by_file_name($file_name){
		$start = strrpos($file_name, '.');
		if($start !== FALSE){
			return substr($file_name, $start);
		}
		return 'unknown';
	}
	
	/**
	 * 保存文件
	 * @param $data
	 * @param $file_name
	 */
	function save_file(&$data, $file_name){
		$type = $this->get_type_by_file_name($file_name);
		$local_name = md5(microtime()).$type;
		$dir = MAILER_ATTACHMENT_REL_PAHT.'/tmp/'.$local_name;
		if(file_put_contents(ROOT.$dir, $data)){
			$data = '';
			unset($data);
			return $local_name;
		}else{
			return '';
		}
	}
/**************************************************************************/
	/*
	/*私有
	/*
	/**************************************************************************/
	/**
	 * 验证邮箱与用户ID是否匹配
	 * @param $user_id		用户ID	
	 * @param $mailboxid	邮箱ID
	 * @param $mailboxRow	返回的邮箱配置数组
	 */
	private function checkMailbox($user_id,$mailboxid,& $mailboxRow){
		$mailboxRow = DB::fetchOne("SELECT * FROM ".DB::table('mailer')." WHERE mailer_id=".$mailboxid." and user_id=".$user_id);
		if(count($mailboxRow) == 0){
			return false;//邮箱不存在
		}else{
			return true;//邮箱存在
		}
	}
	
	/**
	 * 迭代删除文件夹
	 * @param unknown_type $dir
	 */
	private function mailerDeleteDir($dir) 
	{ 
		$dh=opendir($dir);   
	    while ($file=readdir($dh)) {  // readdir函数返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回   
	        if($file!="." && $file!="..") {       
	            $fullpath=$dir."/".$file;   
	            if(!is_dir($fullpath)) {  // is_dir函数：如果文件名存在并且为目录则返回 TRUE     
	               unlink($fullpath);   // unlink函数删除文件   
	            } else {   
	               mailerDeleteDir($fullpath);   
	            }   
	        }   
	    }   
	    closedir($dh);       
	    if(rmdir($dir)) {  // rmdir函数删除目录           
	        return true;          
	    } else {        
	        return false;   
	    }  
	
	}
}

?>